# -*- coding: utf-8 -*-
import base64
import os
import uuid

from odoo import api, fields, models, _, tools
from odoo.osv import expression
from odoo.exceptions import UserError, ValidationError
try:
    from docxtpl import DocxTemplate
except Exception:
    raise UserError("请安装包：pip install docxtpl")


class BankInquiryLetter(models.Model):
    _name = 'bank.inquiry.letter'
    _description = "银行询证函"

    name = fields.Char(string="银行")
    bank_number = fields.Char(string="银行账号")
    bank_branch = fields.Char(string="分支机构")
    my_company = fields.Char(string="本公司")
    my_company_account = fields.Char(string="本公司账户")
    account_company = fields.Char(string='会计事务所')
    account_employee = fields.Char(string='会计人员')
    year = fields.Char(string="年度")
    text = fields.Text(string="备注")

    bank_deposit_ids = fields.One2many('inquiry.bank.deposit', 'bank_inquiry_id', string="银行存款")
    bank_borrow_ids = fields.One2many('inquiry.bank.borrow', 'bank_inquiry_id', string="银行借贷")
    logout_account_ids = fields.One2many('inquiry.logout.account', 'bank_inquiry_id', string="注销账户")
    entrust_loan_ids = fields.One2many('inquiry.entrust.loan', 'bank_inquiry_id', string="作为委托人的委托贷款")
    entrust_borrow_loan_ids = fields.One2many('inquiry.entrust.loan.borrow', 'bank_inquiry_id', string="作为借款人的委托贷款")
    security_other_ids = fields.One2many('inquiry.bank.security.other', 'bank_inquiry_id', string="本公司为其他单位提供的担保")
    security_my_ids = fields.One2many('inquiry.bank.security.my', 'bank_inquiry_id', string="贵行向本公司提供的担保")
    unpaid_honour_bills_ids = fields.One2many('inquiry.unpaid.honour.bills', 'bank_inquiry_id', string="未支付的银行承兑汇票")
    unpaid_commercial_bills_ids = fields.One2many('inquiry.unpaid.commercial.bills', 'bank_inquiry_id', string="未到期的商业汇票")
    collection_commercial_bills_ids = fields.One2many('inquiry.collection.commercial.bills', 'bank_inquiry_id', string="托收的商业汇票")
    irrevocable_letter_credit_ids = fields.One2many('inquiry.irrevocable.letter.credit', 'bank_inquiry_id', string="不可撤销信用证")
    foreign_exchange_contract_ids = fields.One2many('inquiry.foreign.exchange.contract', 'bank_inquiry_id', string="外汇买卖合约")
    securities_property_documents_ids = fields.One2many('inquiry.securities.property.documents', 'bank_inquiry_id', string="证券或其他产权文件")
    unexpired_financial_products_ids = fields.One2many('inquiry.unexpired.financial.products', 'bank_inquiry_id', string="未到期银行理财产品")

    def _get_table_1(self):
        _list  =[]
        for rec in self.bank_deposit_ids:
            _list.append({
                'a': rec.account_name or ' ',
                'b': rec.bank_number or ' ',
                'c': rec.currency or ' ',
                'd': rec.rate or ' ',
                'e': rec.account_type or ' ',
                'f': rec.account_balance or ' ',
                'g': dict(rec.fields_get(allfields=['is_cash_sweep'])['is_cash_sweep']['selection'])[rec.is_cash_sweep] if rec.is_cash_sweep else ' ',
                'h': rec.start_date or ' ',
                'i': rec.end_date or ' ',
                'j': dict(rec.fields_get(allfields=['is_cash_freeze'])['is_cash_freeze']['selection'])[rec.is_cash_freeze] if rec.is_cash_freeze else ' ',
                'k': rec.note or ' ',
            })
        return _list

    def _get_table_2(self):
        _list  =[]
        for rec in self.bank_borrow_ids:
            _list.append({
                'a': rec.borrow_user_name or ' ',
                'b': rec.borrow_user_number or ' ',
                'c': rec.currency or ' ',
                'd': rec.account_balance or ' ',
                'e': rec.borrow_date or ' ',
                'f': rec.due_date or ' ',
                'g': rec.rate or ' ',
                'h': rec.guarantor or ' ',
                'i': rec.note or ' ',
            })
        return _list

    def _get_table_3(self):
        _list  =[]
        for rec in self.logout_account_ids:
            _list.append({
                'a': rec.account_name or ' ',
                'b': rec.bank_number or ' ',
                'c': rec.currency or ' ',
                'd': rec.logout_date or ' ',
            })
        return _list

    def _get_table_4(self):
        _list  =[]
        for rec in self.entrust_loan_ids:
            _list.append({
                'a': rec.borrow_user_name or ' ',
                'b': rec.borrow_user_number or ' ',
                'c': rec.fund_lender or ' ',
                'd': rec.currency or ' ',
                'e': rec.rate or ' ',
                'f': rec.account_balance or ' ',
                'g': "%s~%s" % (rec.start_date, rec.end_date) or ' ',
                'h': rec.note or ' ',
            })
        return _list

    def _get_table_5(self):
        _list  =[]
        for rec in self.entrust_borrow_loan_ids:
            _list.append({
                'a': rec.borrow_user_name or ' ',
                'b': rec.borrow_user_number or ' ',
                'c': rec.fund_lender or ' ',
                'd': rec.currency or ' ',
                'e': rec.rate or ' ',
                'f': rec.account_balance or ' ',
                'g': "%s~%s" % (rec.start_date, rec.end_date) or ' ',
                'h': rec.note or ' ',
            })
        return _list

    def _get_table_6(self):
        _list  =[]
        for rec in self.security_other_ids:
            _list.append({
                'a': rec.security_user_name or ' ',
                'b': rec.borrow_user_number or ' ',
                'c': rec.currency or ' ',
                'd': rec.security_amount or ' ',
                'e': rec.security_date or ' ',
                'f': rec.security_contract_number or ' ',
                'g': rec.note or ' ',
            })
        return _list

    def _get_table_7(self):
        _list  =[]
        for rec in self.security_my_ids:
            _list.append({
                'a': rec.security_user_name or ' ',
                'b': rec.borrow_user_number or ' ',
                'c': rec.currency or ' ',
                'd': rec.security_amount or ' ',
                'e': rec.security_date or ' ',
                'f': rec.security_contract_number or ' ',
                'g': rec.note or ' ',
            })
        return _list

    def _get_table_8(self):
        _list  =[]
        for rec in self.unpaid_honour_bills_ids:
            _list.append({
                'a': rec.bill_number or ' ',
                'b': rec.jiesuanaccount_number or ' ',
                'c': rec.currency or ' ',
                'd': rec.bill_amount or ' ',
                'e': rec.bill_date or ' ',
                'f': rec.due_date or ' ',
                'g': rec.collateral or ' ',
            })
        return _list

    def _get_table_9(self):
        _list  =[]
        for rec in self.unpaid_commercial_bills_ids:
            _list.append({
                'a': rec.commercial_number or ' ',
                'b': rec.user_name or ' ',
                'c': rec.currency or ' ',
                'd': rec.bill_amount or ' ',
                'e': rec.bill_date or ' ',
                'f': rec.due_date or ' ',
                'g': rec.discounted_date or ' ',
                'h': rec.discounted_rate or ' ',
                'i': rec.collateral_amount or ' ',
            })
        return _list

    def _get_table_10(self):
        _list  =[]
        for rec in self.collection_commercial_bills_ids:
            _list.append({
                'a': rec.commercial_number or ' ',
                'b': rec.user_name or ' ',
                'c': rec.currency or ' ',
                'd': rec.bill_amount or ' ',
                'e': rec.bill_date or ' ',
                'f': rec.due_date or ' ',
            })
        return _list

    def _get_table_11(self):
        _list  =[]
        for rec in self.irrevocable_letter_credit_ids:
            _list.append({
                'a': rec.number or ' ',
                'b': rec.user_name or ' ',
                'c': rec.currency or ' ',
                'd': rec.amount or ' ',
                'e': rec.due_date or ' ',
                'f': rec.unuse_amount or ' ',
            })
        return _list

    def _get_table_12(self):
        _list  =[]
        for rec in self.foreign_exchange_contract_ids:
            _list.append({
                'a': rec.my_type or ' ',
                'b': rec.number or ' ',
                'c': rec.sell_currency or ' ',
                'd': rec.buy_currency or ' ',
                'f': rec.amount or ' ',
                'g': rec.exchange_rate or ' ',
                'h': rec.use_date or ' ',
            })
        return _list

    def _get_table_13(self):
        _list  =[]
        for rec in self.securities_property_documents_ids:
            _list.append({
                'a': rec.name or ' ',
                'b': rec.number or ' ',
                'c': rec.count or ' ',
                'd': rec.currency or ' ',
                'e': rec.amount or ' ',
            })
        return _list

    def _get_table_14(self):
        _list  =[]
        for rec in self.unexpired_financial_products_ids:
            _list.append({
                'a': rec.name or ' ',
                'b': dict(rec.fields_get(allfields=['my_type'])['my_type']['selection'])[rec.my_type] if rec.my_type else ' ',
                'c': rec.currency or ' ',
                'd': rec.holding_shares or ' ',
                'e': rec.net_value or ' ',
                'f': rec.buy_date or ' ',
                'g': rec.due_date or ' ',
                'h': rec.is_security or ' ',
            })
        return _list

    def btn_download_bank_inquiry_letter(self):
        template = DocxTemplate('myaddons/2/bank_inquiry/static/files/template_my.docx')
        content = {
            'bank': self.name,
            'bank_branch': self.bank_branch,
            'account_company': self.account_company,
            'year': self.year,
            'my_company_account': self.my_company_account,
            'table1': self._get_table_1(),
            'table2': self._get_table_2(),
            'table3': self._get_table_3(),
            'table4': self._get_table_4(),
            'table5': self._get_table_5(),
            'table6': self._get_table_6(),
            'table7': self._get_table_7(),
            'table8': self._get_table_8(),
            'table9': self._get_table_9(),
            'table10': self._get_table_10(),
            'table11': self._get_table_11(),
            'table12': self._get_table_12(),
            'table13': self._get_table_13(),
            'table14': self._get_table_14(),
        }
        template.render(content)
        fiele_name = '%s银行询证函-%s.docx' % (self.name, uuid.uuid4().hex)
        template.save(fiele_name)
        with open(fiele_name, 'rb') as f:
            data = base64.b64encode(f.read())
            attachment_data = {
                'name': fiele_name,
                'datas': data,
                'type': 'binary',
                'res_model': 'bank.inquiry.letter',
                'res_id': self.id,
            }
            attach = self.env['ir.attachment'].create(attachment_data)
        os.remove('{}'.format(fiele_name))
        return {
            "type": 'ir.actions.act_url',
            "url": '/web/content/%d/?filename=%s' % (attach.id, fiele_name)
        }


class BankDeposit(models.Model):
    _name = 'inquiry.bank.deposit'
    _description = "银行存款"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    account_name = fields.Char(string="账户名称")
    bank_number = fields.Char(string="银行账号")
    currency = fields.Char(string='币种')
    rate = fields.Char(string="利率")
    account_type = fields.Char(string="账户类型")
    account_balance = fields.Float(string="账户余额")
    is_cash_sweep = fields.Selection([('yes', '是'), ('no', '否')], string="是否属于资金归集账户")
    start_date = fields.Date(string="起始日期")
    end_date = fields.Date(string="终止日期")
    is_cash_freeze = fields.Selection([('yes', '是'), ('no', '否')], string="是否存在冻结、担保或其他使用限制")
    note = fields.Char(string="备注")



class BankBorrow(models.Model):
    _name = 'inquiry.bank.borrow'
    _description = "银行借贷"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    borrow_user_name = fields.Char(string="借款人名称")
    borrow_user_number = fields.Char(string="借款账号")
    currency = fields.Char(string='币种')
    account_balance = fields.Float(string="余额")
    borrow_date = fields.Date(string="借款日期")
    due_date = fields.Date(string="到期日期")
    rate = fields.Char(string="利率")
    guarantor = fields.Char(string="抵（质）押品/担保人")
    note = fields.Char(string="备注")



class logoutAccount(models.Model):
    _name = 'inquiry.logout.account'
    _description = "注销账户"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    account_name = fields.Char(string="账户名称")
    bank_number = fields.Char(string="银行账号")
    currency = fields.Char(string='币种')
    logout_date = fields.Date(string="注销账户日")
    note = fields.Char(string="备注")



class EntrustLoan(models.Model):
    _name = 'inquiry.entrust.loan'
    _description = "作为委托人的委托贷款"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    borrow_user_name = fields.Char(string="借款人名称")
    borrow_user_number = fields.Char(string="借款账号")
    fund_lender = fields.Char(string="资金借出方")
    currency = fields.Char(string='币种')
    rate = fields.Char(string="利率")
    account_balance = fields.Float(string="余额")
    start_date = fields.Date(string="贷款开始日期")
    end_date = fields.Date(string="贷款结束日期")
    note = fields.Char(string="备注")


class EntrustLoanBrrow(models.Model):
    _name = 'inquiry.entrust.loan.borrow'
    _description = "作为借款人的委托贷款"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    borrow_user_name = fields.Char(string="借款人名称")
    borrow_user_number = fields.Char(string="借款账号")
    fund_lender = fields.Char(string="资金借出方")
    currency = fields.Char(string='币种')
    rate = fields.Char(string="利率")
    account_balance = fields.Float(string="余额")
    start_date = fields.Date(string="贷款开始日期")
    end_date = fields.Date(string="贷款结束日期")
    note = fields.Char(string="备注")


class BankSecurityOther(models.Model):
    _name = 'inquiry.bank.security.other'
    _description = "本公司为其他单位提供的担保"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    security_user_name = fields.Char(string="被担保人")
    borrow_user_number = fields.Char(string="担保方式")
    currency = fields.Char(string='币种')
    security_amount = fields.Float(string="担保金额")
    security_date = fields.Date(string="担保到期日")
    security_contract_number = fields.Char(string="担保合同编号")
    note = fields.Char(string="备注")


class BankSecurityMy(models.Model):
    _name = 'inquiry.bank.security.my'
    _description = "贵行向本公司提供的担保"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    security_user_name = fields.Char(string="被担保人")
    borrow_user_number = fields.Char(string="担保方式")
    currency = fields.Char(string='币种')
    security_amount = fields.Float(string="担保金额")
    security_date = fields.Date(string="担保到期日")
    security_contract_number = fields.Char(string="担保合同编号")
    note = fields.Char(string="备注")


class UnpaidhonourBills(models.Model):
    _name = 'inquiry.unpaid.honour.bills'
    _description = "未支付的银行承兑汇票"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    bill_number = fields.Char(string="银行承兑汇票号码")
    jiesuanaccount_number = fields.Char(string="结算账户账号")
    currency = fields.Char(string='币种')
    bill_amount = fields.Float(string="票面金额")
    bill_date = fields.Date(string="出票日")
    due_date = fields.Date(string="到期日")
    collateral = fields.Char(string="抵（质）押品")
    note = fields.Char(string="备注")



class UnpaidCommercialBills(models.Model):
    _name = 'inquiry.unpaid.commercial.bills'
    _description = "未到期的商业汇票"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    commercial_number = fields.Char(string="商业汇票号码")
    user_name = fields.Char(string="承兑人名称")
    currency = fields.Char(string='币种')
    bill_amount = fields.Float(string="票面金额")
    bill_date = fields.Date(string="出票日")
    due_date = fields.Date(string="到期日")
    discounted_date = fields.Date(string="贴现日")
    discounted_rate = fields.Char(string="贴现率")
    collateral_amount = fields.Float(string="贴现净额")
    note = fields.Char(string="备注")


class CollectionCommercialBills(models.Model):
    _name = 'inquiry.collection.commercial.bills'
    _description = "托收的商业汇票"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    commercial_number = fields.Char(string="商业汇票号码")
    user_name = fields.Char(string="承兑人名称")
    currency = fields.Char(string='币种')
    bill_amount = fields.Float(string="票面金额")
    bill_date = fields.Date(string="出票日")
    due_date = fields.Date(string="到期日")
    note = fields.Char(string="备注")


class IrrevocableLetterCredit(models.Model):
    _name = 'inquiry.irrevocable.letter.credit'
    _description = "不可撤销信用证"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    number = fields.Char(string="信用证号码")
    user_name = fields.Char(string="受益人")
    currency = fields.Char(string='币种')
    amount = fields.Float(string="票面金额")
    due_date = fields.Date(string="到期日")
    unuse_amount = fields.Float(string="未使用金额")
    note = fields.Char(string="备注")



class ForeignExchangeContract(models.Model):
    _name = 'inquiry.foreign.exchange.contract'
    _description = "外汇买卖合约"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    my_type = fields.Char(string="类别")
    number = fields.Char(string="合约号码")
    sell_currency = fields.Char(string='贵行卖出币种')
    buy_currency = fields.Char(string='贵行买入币种')
    user_name = fields.Char(string="受益人")
    amount = fields.Float(string="履行的合约买卖金额")
    exchange_rate = fields.Char(string="汇率")
    use_date = fields.Date(string="交收日期")
    note = fields.Char(string="备注")



class SecuritiesPropertyDocuments(models.Model):
    _name = 'inquiry.securities.property.documents'
    _description = "证券或其他产权文件"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    name = fields.Char(string="证券或其他产权文件名称")
    number = fields.Char(string="证券代码或产权文件编号")
    count = fields.Float(string='数量')
    currency = fields.Char(string='币种')
    amount = fields.Float(string="金额")
    note = fields.Char(string="备注")


class UnexpiredFinancialProducts(models.Model):
    _name = 'inquiry.unexpired.financial.products'
    _description = "未到期银行理财产品"

    bank_inquiry_id = fields.Many2one('bank.inquiry.letter', string='银行询证函')
    name = fields.Char(string="产品名称")
    my_type = fields.Selection([('closed', '封闭式'), ('open', '开放式')], string="产品类型（封闭式/开放式）")
    currency = fields.Char(string='币种')
    holding_shares = fields.Char(string='持有份额')
    net_value = fields.Float(string="产品净值")
    buy_date = fields.Date(string="购买日")
    due_date = fields.Date(string="到期日")
    is_security = fields.Boolean(string="是否被用于担保或存在其他使用限制")
    note = fields.Char(string="备注")



